# 使用轻量级Python镜像（固定为Debian bullseye以提升稳定性）
FROM python:3.10-slim-bullseye

# 设置环境变量
ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1 \
    FLASK_APP=app.py \
    FLASK_ENV=production \
    DEBIAN_FRONTEND=noninteractive \
    ACCEPT_EULA=Y

# 设置工作目录
WORKDIR /app

# 创建非root用户
RUN groupadd -r appuser && useradd -r -g appuser appuser

# 一次性安装所有依赖，减少层数和内存使用
RUN apt-get update && apt-get install -y --no-install-recommends \
    gcc \
    g++ \
    unixodbc-dev \
    freetds-dev \
    freetds-bin \
    unixodbc \
    && apt-get clean \
    && rm -rf /var/lib/apt/lists/* \
    && rm -rf /tmp/* \
    && rm -rf /var/tmp/*

# 安装微软 SQL Server ODBC 驱动（使用更稳定的安装方法）
RUN apt-get update && apt-get install -y --no-install-recommends curl gnupg ca-certificates \
    && curl -fsSL https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor -o /usr/share/keyrings/microsoft-prod.gpg \
    && echo "deb [arch=amd64,arm64,armhf signed-by=/usr/share/keyrings/microsoft-prod.gpg] https://packages.microsoft.com/debian/11/prod bullseye main" > /etc/apt/sources.list.d/mssql-release.list \
    && apt-get update \
    && ACCEPT_EULA=Y apt-get install -y --no-install-recommends msodbcsql18 || \
       (echo "ODBC 18 installation failed, trying ODBC 17..." && \
        ACCEPT_EULA=Y apt-get install -y --no-install-recommends msodbcsql17) \
    && apt-get clean \
    && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

# 配置pip镜像源和超时设置
RUN pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple/ \
    && pip config set global.trusted-host pypi.tuna.tsinghua.edu.cn \
    && pip config set global.timeout 300

# 安装Python依赖
COPY requirements.txt .
RUN pip install --no-cache-dir --upgrade pip --timeout 300 \
    && pip install --no-cache-dir -r requirements.txt --timeout 300 \
    && pip cache purge

# 复制应用文件
COPY app.py .
COPY templates/ templates/

# 创建数据库目录并设置权限
RUN mkdir -p /app/data && \
    chown -R appuser:appuser /app

# 切换到非root用户
USER appuser

# 暴露端口
EXPOSE 7629

# 健康检查
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
    CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:7629')" || exit 1

# 启动命令
CMD ["python", "app.py"]